package com.example.service.impl;

import com.example.exception.DataUploadException;
import com.example.info.DeviceInfo;
import com.example.info.SampleInfo;
import com.example.mapper.DeviceDataMapper;
import com.example.pojo.PageResult;
import com.example.service.DeviceDataService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class DeviceDataServiceImpl implements DeviceDataService {


    private SampleInfo sampleInfo = new SampleInfo();
    private DeviceInfo deviceInfo = new DeviceInfo();

    private String baseDir = "C:\\project\\serImg\\digitalSampleMachine";

    //保存图片
    @Override
    public String uploadImage(MultipartFile file) throws IOException {
        // 验证文件类型
        if (!isImage(file)) {
            throw new DataUploadException("只允许上传图片文件（PNG/JPG/JPEG）");
        }

        // 生成存储路径
        Path targetPath = generateTargetPath(file);

        // 保存文件
        Files.createDirectories(targetPath.getParent());
        file.transferTo(targetPath);

        return targetPath.toString();
    }

    private Path generateTargetPath(MultipartFile file) {
        // 时间分层目录
        String timeDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd/HH"));

        // 直接使用原始文件名（保留原名称）
        String originalFilename = file.getOriginalFilename();

        // 组合路径：基础目录 + 时间目录 + 原始文件名
        return Paths.get(baseDir, timeDir, originalFilename);
    }

    private boolean isImage(MultipartFile file) {
        String mimeType = file.getContentType();
        return mimeType != null && mimeType.startsWith("image/");
    }




    @Autowired
    private DeviceDataMapper deviceDataMapper;

    //获取设备信息
    public List<DeviceInfo> getData() {
        List<DeviceInfo> deviceInfos = deviceDataMapper.getData();
        deviceInfos.forEach(deviceInfo -> {
            deviceInfo.setMachineName(deviceDataMapper.getMachineName(deviceInfo.getMachineID()));
            deviceInfo.setIPAddress(deviceDataMapper.getIPAddress(deviceInfo.getMachineID()));
            deviceInfo.setIsConnected(deviceDataMapper.getIsConnected(deviceInfo.getMachineID()));
        });
        return deviceInfos;
    }

    //新增设备信息
    public void save(DeviceInfo deviceInfo) {
        deviceDataMapper.save(deviceInfo);
    }


    //获取所有设备信息
    public List<DeviceInfo> getAll() {
        return deviceDataMapper.getAll();
    }

    //分页获取所有设备信息
    public PageResult page(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<DeviceInfo> deviceInfoList = deviceDataMapper.getAllDesc();
        deviceInfoList.forEach(deviceInfo -> {
            deviceInfo.setMachineName(deviceDataMapper.getMachineName(deviceInfo.getMachineID()));
            deviceInfo.setIPAddress(deviceDataMapper.getIPAddress(deviceInfo.getMachineID()));
        });
        Page<DeviceInfo> p = (Page<DeviceInfo>) deviceInfoList;
        return new PageResult(p.getTotal(), p.getResult());
    }

    //如果数据库数据总数超过1000条，则保留最新的1000条数据，删除多余的数据
    public void deleteOldData() {
        int count = deviceDataMapper.getCount();
        if (count > 1000) {
            int deleteCount = count - 1000;
            for (int i = 0; i < deleteCount; i++) {
                deviceDataMapper.deleteOldData();
            }
        }
    }
}
